import {get, post} from '@/utils/request'

import { fetchEventSource } from "@microsoft/fetch-event-source";
import config from '@/config'

/** 查询未读 */
export function findNoShowSse(success,fail) {
    const url = config.baseURL+ "/api/notification/findNoShowSse?token="+window.localStorage.getItem('token'); //
    let eventSource = new EventSource(url,{
        withCredentials: true,
        encoding: 'UTF-8',
        headers: {
            "Content-Type": "application/json",
            "token": window.localStorage.getItem('token')
        }
    });
    eventSource.onmessage = (event) => {
        if(event.data === '' || event.data === null){
            return;
        }
        const newMessage = JSON.parse(event.data);
        success(newMessage);
    };
    eventSource.onerror = (error) => {
        fail();
        console.error('SSE连接失败', error);
        this.eventSource.close(); // 可以在这里处理重连逻辑
    };
}
export function findNoRead() {
    return get("/api/notification/findNoRead", {});
}

/** 删除消息 */
export function remove(params) {
    return post("/api/notification/remove", params);
}

/** 查询消息前20条  */
export function findList() {
    return get("/api/notification/findList", {});
}

/** 查询消息分页  */
export function findPage(params) {
    return post("/api/notification/findPage", params);
}

/** 查询所有未读数量  */
export function findNoReadCount() {
    return post("/api/notification/findNoReadCount", {});
}

/** 已读多个  */
export function read(params) {
    return post("/api/notification/read", params);
}

/** 已读全部  */
export function readAll() {
    return post("/api/notification/readAll", {});
}

/** 测试发送消息  */
export function sendTest(params) {
    return post("/api/notification/sendTest", params);
}

export function findNoReadCountSse(success,fail) {
    const url = config.baseURL+ "/api/notification/findNoReadCountSSE?token="+window.localStorage.getItem('token'); //
    let eventSource = new EventSource(url,{
        withCredentials: true,
        encoding: 'UTF-8',
        headers: {
            "Content-Type": "application/json",
            "token": window.localStorage.getItem('token')

        }
    });
    eventSource.onmessage = (event) => {
        const newMessage = JSON.parse(event.data);
        success(newMessage);
    };
    eventSource.onerror = (error) => {
        fail();
        console.error('SSE连接失败', error);
        this.eventSource.close(); // 可以在这里处理重连逻辑
    };
}


